import cv2
import numpy as np


class HSV_TrackBar:
    def __init__(self):
        cv2.namedWindow("TrackBars")
        cv2.resizeWindow("TrackBars", 600, 300)

        cv2.createTrackbar("Hue Min", "TrackBars", 0, 179, self.empty)
        cv2.createTrackbar("Hue Max", "TrackBars", 179, 179, self.empty)
        cv2.createTrackbar("Sat Min", "TrackBars", 0, 255, self.empty)
        cv2.createTrackbar("Sat Max", "TrackBars", 255, 255, self.empty)
        cv2.createTrackbar("Val Min", "TrackBars", 0, 255, self.empty)
        cv2.createTrackbar("Val Max", "TrackBars", 255, 255, self.empty)

    def empty(self, a):
        pass


colorbar = HSV_TrackBar()
capture = cv2.VideoCapture(0)

while True:
    success, frame = capture.read()
    img = cv2.resize(frame, dsize=None, fx=0.3, fy=0.3)
    # img = frame
    imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    h_min = cv2.getTrackbarPos("Hue Min", "TrackBars")
    h_max = cv2.getTrackbarPos("Hue Max", "TrackBars")
    s_min = cv2.getTrackbarPos("Sat Min", "TrackBars")
    s_max = cv2.getTrackbarPos("Sat Max", "TrackBars")
    v_min = cv2.getTrackbarPos("Val Min", "TrackBars")
    v_max = cv2.getTrackbarPos("Val Max", "TrackBars")
    print(h_min, h_max, s_min, s_max, v_min, v_max)

    lower = np.array([h_min, s_min, v_min])
    upper = np.array([h_max, s_max, v_max])
    mask = cv2.inRange(imgHSV, lower, upper)
    imgResult = cv2.bitwise_and(img, img, mask=mask)

    # cv2.imshow("original", img)
    # cv2.imshow("mask", mask)
    # cv2.imshow("imgResult", imgResult)

    cat_pic = np.hstack([img, cv2.merge([mask, mask, mask]), imgResult])
    cv2.imshow("result", cat_pic)
    key = cv2.waitKey(1)
    if key == ord('q'):
        break

cv2.destroyAllWindows()
